#!/bin/bash

# 定义配置文件路径
CONF_FILE="./config/wpa_supplicant.conf"

# 从配置文件中提取 SSID，并去除首尾空格
SSID=$(grep 'ssid=' "$CONF_FILE" | sed 's/^[[:space:]]*ssid="\([^"]*\)"[[:space:]]*$/\1/')

if [ -z "$SSID" ]; then
    # echo "无法从 $CONF_FILE 中提取 SSID，退出。"
    exit 1
fi

# 检查 wlan0 接口是否存在
if ! ifconfig wlan0 &> /dev/null; then
    # echo "wlan0 接口不存在，退出。"
    exit 1
fi

FOUND=false
echo "wifi ssid: $SSID"
SCAN_RESULTS=$(iwlist wlan0 scan | grep "$SSID")
echo "scan result: $SCAN_RESULTS"
if [ -n "$SCAN_RESULTS" ]; then
    FOUND=true
fi

if ! $FOUND; then
    # echo "未搜索到 SSID 为 $SSID 的 Wi-Fi 网络，退出。"
    exit 1
fi

# 继续执行原脚本逻辑
# ifconfig eth0 down
rfkill unblock wifi
pkill wpa_supplicant
wpa_supplicant -i wlan0 -c "$CONF_FILE" -B
ifconfig wlan0 down
sleep 1
ifconfig wlan0 up
# 运行 udhcpc 时带上 -R 选项，这样在 udhcpc 退出时会自动释放 IP 地址
udhcpc -i wlan0 -R